<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>取消请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.2/axios.js"></script>
  </head>

  <body>
    <button>发送请求</button>
    <button>取消请求</button>
    <script>
      let btns = document.querySelectorAll("button");
      //1. 声明外部变量
      let cancel = null;

      btns[0].onclick = async function () {
        //2. 在配置对象中声明 cancelToken
        let res = await axios.get('http://127.0.0.1:8080/movie', {
            cancelToken: new axios.CancelToken(c => {
                cancel = c;
            })
        })
        console.log(res);
      };

      btns[1].onclick = async function () {
        //3. 执行 cancel 函数
        if(!cancel) return;
        cancel();
      };
    </script>
  </body>
</html>
